package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@Slf4j
//指定过滤器的名称和拦截路径
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse reponse = (HttpServletResponse)servletResponse;

        //过滤器具体的处理逻辑如下:
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        //打印日志：用于功能的测试
        log.info("本次请求为：{}",requestURI);
            //定义不需要处理的请求
        String[] urls = new String[]{
                //动态请求路径
                "/employee/login",
                "/employee/logout",
                "/common/**",
                //静态页面请求路径
                "/backend/**",
                "/front/**",
                //手机验证登录
                "/user/sendMsg",//移动端发送短信
                "/user/login"//移动端登录
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3、如果不需要处理，则直接放行
        if (check){
            //打印日志：用于功能的测试
            log.info("本次请求{}不需要处理",requestURI);
            //放行
            filterChain.doFilter(request,reponse);
            return;
        }
        //4-1、判断登录状态，如果已登录，则直接放行（适用于后台管理系统的员工登录）
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null){
            //打印日志：用于功能的测试
            log.info("用户已经登录，用户id为“{}",employee);

            //获取当前的线程id
            long id = Thread.currentThread().getId();
            log.info("当前线程的id为：{}",id);
            //将当前用户的id存入ThreadLocal当中
            Long empId = (Long) employee;
            BaseContext.setCurrentId(empId);

            //放行
            filterChain.doFilter(request,reponse);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行（适用于移动端用户的登录）
        Object user = request.getSession().getAttribute("user");
        if (user != null){
            //打印日志：用于功能的测试
            log.info("用户已经登录，用户id为“{}",user);

            //获取当前的线程id
            long id = Thread.currentThread().getId();
            log.info("当前线程的id为：{}",id);
            //将当前用户的id存入ThreadLocal当中
            Long userId = (Long) user;
            BaseContext.setCurrentId(userId);

            //放行
            filterChain.doFilter(request,reponse);
            return;
        }
        //打印日志：用于功能的测试
        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流的方式向客户端页面响应数据
        reponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls 不需要处理的请求
     * @param requestURI 本次请求的URI
     * @return
     */
    public boolean check(String[] urls , String requestURI){
        //遍历不需要处理的请求
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match == true){
                return true;
            }
        }
        return false;
    }
}
